package Controller;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import javax.swing.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        String shenfen =  request.getParameter("user_type");
        String id =  request.getParameter("id");
        String name = request.getParameter("name");
        String password = request.getParameter("pwd");
        String phone = request.getParameter("phone");
        int identity = Integer.parseInt(shenfen);
        PrintWriter out = response.getWriter();
        //            HttpSession session = request.getSession();
        try {
            Context context = new InitialContext();
            Context contextNeeded = (Context) context.lookup("java:comp/env");
            DataSource ds = (DataSource) contextNeeded.lookup("wq");// 获得连接池。
            Connection con = null;
            ResultSet rs;
            String sql;
            PreparedStatement pstmt;
            con = ds.getConnection();//获得数据源

            sql = "insert into user(id,name,password,identity,phone) values(?,?,?,?,?)";
            try {
                pstmt = con.prepareStatement(sql);
                pstmt.setString(1,id);
                pstmt.setString(2,name);
                pstmt.setString(3,password);
                pstmt.setInt(4,identity);
                pstmt.setString(5,phone);
                pstmt.executeUpdate();
                response.sendRedirect("jsp/login.jsp");
            }catch (SQLException e){
                response.getWriter().write("<script language='javascript'>alert('注册失败！');" +
                        "window.location.href='/jsp/register.jsp';</script>");
                response.sendRedirect("jsp/register.jsp");
            }

            con.close();
        }catch(SQLException | NamingException e){
            System.out.println("加载不成功");
        }
    }
}
